<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Sms;
use App\Traits\ValidationTrait;
use Exception;
use Illuminate\Http\Request;

/**
 * 忘记密码
 */
class ForgetPasswordController extends Controller
{
    use ValidationTrait;
    /**
     * 忘记密码
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function forget_password(Request $request)
    {
        try {
            $status = 0;
            $data   = [];
            //验证
            $validator = $this->verify($request, 'validation.register_account'); //验证规则同注册
            if ($validator->fails()) {
                $messages = $validator->messages()->first();

                throw new Exception($messages);
            }
            $phone    = $request->get('phone');
            $code     = $request->get('code');
            $password = $request->get('password');
            $repass   = $request->get('repass');

            if ($password != $repass) {
                throw new Exception('两次密码不一致！');
            }

            /*$sms = Sms::where(['phone' => $phone, 'type' => 2])->first();
            //验证码过期
            if (time() > $sms->expired_at) {
            throw new Exception('验证码已过期！');
            }
            //验证码错误
            if ($sms->code != $code) {
            //if ($code != '666666') {
            throw new Exception('验证码错误！');
            }*/

            $user = User::where(['phone' => $phone])->whereIn('type', [1, 3, 4])->first(); //查找用户
            if (!$user) {
                throw new Exception("用户不存在！");
            }

            $user->update([
                'password' => md5($password . config('public.password_key')),
            ]);

            $status           = 1;
            $msg              = '修改成功！';
            $data['user_id']  = $user->userID;
            $data['nickname'] = $user->nickname;
            $data['headimg']  = $user->headimg;

        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        return response()->json(['status' => $status, 'msg' => $msg, 'data' => $data]);
    }
}
